package com.edu.user.controller;

import com.alibaba.fastjson.JSON;
import com.edu.api.entity.common.Pageable;
import com.edu.api.entity.common.ResponseDTO;
import com.edu.api.entity.user.User;
import com.edu.user.minio.MinioUtilS;
import com.edu.user.service.UserService;
import com.edu.user.wx.HttpClientUtil;
import com.edu.user.wx.Token;
import com.edu.user.wx.WxUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

/**
 * @description: 描述
 * @author: xnylh
 * @createDate: 2023/1/5 0005 16:02
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private MinioUtilS minioUtilS;
    @Value("${minio.endpoint}")
    private String address;
    @Value("${minio.bucketName}")
    private String bucketName;

    @Autowired
    private UserService userService;

    private ResponseDTO dto = null; // 是否用微信登录成功，dto为null，则尚未登录

    @GetMapping("wxlogin")
    public String wxlogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 微信官方发给我们一个临时凭证
        String code = request.getParameter("code");
//        System.out.println("【临时凭证】code = " + code);
        // 2. 通过code，去微信官方申请一个正式的token（令牌）
        String getTokenByCode_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxd99431bbff8305a0&secret=60f78681d063590a469f1b297feff3c4&code=" + code + "&grant_type=authorization_code";
        String tokenString = HttpClientUtil.doGet(getTokenByCode_url);
//        System.out.println("tokenString = " + tokenString);
        // 将json格式的token字符串转换成实体对象，方便存和取
        Token token = JSON.parseObject(tokenString, Token.class);

        // 3. 通过token，去微信官方获取用户的信息
        String getUserByToken_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token.getAccess_token() + "&openid=" + token.getOpenid();
        String userinfoString = HttpClientUtil.doGet(getUserByToken_url);
//        System.out.println("userinfoString = " + userinfoString);
        // 将json格式的user字符串转换成实体对象，方便存和取
        WxUser wxUser = JSON.parseObject(userinfoString, WxUser.class);
//        System.out.println("微信昵称 = " + wxUser.getNickname());
//        System.out.println("微信头像 = " + wxUser.getHeadimgurl());

        // 泡泡的业务流程！ 需要 手机号（wxUser.getUnionid()）和密码（wxUser.getUnionid()）,头像和昵称
        dto = new ResponseDTO();
            // 未注册，自动注册并登录
            dto = userService.register(wxUser.getUnionid(),wxUser.getUnionid(),wxUser.getNickname(),request.getRemoteAddr(),wxUser.getHeadimgurl());
        response.sendRedirect("http://localhost:8080/login");
        return null;
    }

    @GetMapping("checkWxStatus")
    public ResponseDTO checkWxStatus(){
        return this.dto;
    }

    @GetMapping("logout")
    public Object logout(){
        this.dto = null;
        return null;
    }

    @PutMapping("/updatePassword")
    public ResponseDTO updatePassword(@RequestBody Map<String,String> map){
        return userService.updatePassword(map.get("id"),map.get("newPwd"),map.get("oldPwd"));
    }

    @PutMapping("/updateUser")
    public ResponseDTO updateUser(@RequestBody User user){
        return userService.updateUser(user);
    }

    @GetMapping("/login")
    public ResponseDTO register(String phone, String password, HttpServletRequest request){
        return userService.register(phone,password,"", request.getRemoteAddr(),"");
    }

    @PostMapping("backstageLogin")
    public ResponseDTO backstageLogin(@RequestBody Map<String,String> map){
        return userService.backstageLogin(map.get("phone"),map.get("password"));
    }

    @PostMapping("/getUserInfo")
    public ResponseDTO getUserInfo(HttpServletRequest request){
        return userService.getUserInfo(request);
    }

    @PostMapping("/upload")
    public Object upload(MultipartFile file) {
        List<String> upload = minioUtilS.upload(new MultipartFile[]{file});
        return address+"/"+bucketName+"/"+upload.get(0);
    }

    @GetMapping("/getAllUser")
    public ResponseDTO getAllUser(Integer page,Integer size,User user) throws ParseException {
        Pageable pageable = new Pageable();
        pageable.setPage(page);
        pageable.setSize(size);
        return userService.getAllUser(pageable,user);
    }

    @PostMapping("/updateUserStatus")
    public ResponseDTO updateUserStatus(@RequestBody Map<String,String> map){
        return userService.updateUserStatus(Integer.valueOf(map.get("id")),map.get("status"));
    }

    @PostMapping("/addOrUpdateBackStageUser")
    public ResponseDTO addOrUpdateBackStageUser(@RequestBody User user,HttpServletRequest request){
        return userService.addOrUpdateBackStageUser(user,request);
    }

    @DeleteMapping("/deleteBackstageUser")
    public ResponseDTO deleteUser(@RequestBody List<Integer> ids){
        return userService.deleteUserByIds(ids);
    }

    @GetMapping("/resetBackstagePwd")
    public ResponseDTO resetBackstagePwd(Integer id){
        return userService.resetBackstagePwdById(id);
    }
}
